package org.example.ag_notes.controller;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.example.ag_notes.dto.article.TreeNodeDto;
import org.example.ag_notes.dto.response.Response;
import org.example.ag_notes.exception.AuthenticationException;
import org.example.ag_notes.exception.BusinessException;
import org.example.ag_notes.service.TreeNodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Tag(name = "树节点管理", description = "管理树形结构节点（目录/文章）")
@RestController
@RequestMapping("/api/node")
public class TreeNodeController {

    @Autowired
    private TreeNodeService treeNodeService;

    @Operation(summary = "添加节点", description = "添加目录或文章节点")
    @ApiResponse(responseCode = "200", description = "成功")
    @ApiResponse(responseCode = "400", description = "参数错误")
    @ApiResponse(responseCode = "500", description = "系统错误")
    @PostMapping("add")
    public ResponseEntity<Response<?>> addNode(
            @RequestBody TreeNodeDto dto,
            @RequestHeader("Authorization") String accessToken
    ) {
        try {
            return ResponseEntity.ok(
                    Response.success("节点添加成功", treeNodeService.addNode(dto, accessToken))
            );
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(
                    Response.error(400, e.getMessage())
            );
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(
                    Response.error(500, "系统繁忙，请稍后重试")
            );
        }
    }

    @Operation(summary = "获取用户节点树", description = "获取当前用户的完整树形结构")
    @ApiResponse(responseCode = "200", description = "成功")
    @ApiResponse(responseCode = "401", description = "未授权")
    @ApiResponse(responseCode = "500", description = "系统错误")
    @GetMapping("get")
    public ResponseEntity<Response<List<TreeNodeDto>>> getUserTree(
            @RequestHeader("Authorization") String token
    ) {
        try {
            List<TreeNodeDto> tree = treeNodeService.listUserNodes(token);
            return ResponseEntity.ok(
                    Response.success("查询成功", tree)
            );
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(
                    Response.error(400, e.getMessage())
            );
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(
                    Response.error(500, "获取数据失败")
            );
        }
    }

    @Operation(summary = "更新单个节点", description = "更新单个节点的信息")
    @ApiResponse(responseCode = "200", description = "更新成功")
    @ApiResponse(responseCode = "400", description = "请求参数错误")
    @ApiResponse(responseCode = "401", description = "未授权")
    @ApiResponse(responseCode = "500", description = "系统错误")
    @PutMapping("update")
    public ResponseEntity<Response<TreeNodeDto>> updateNode(
            @RequestHeader("Authorization") String token,
            @RequestBody TreeNodeDto dto
    ) {
        try {
            TreeNodeDto node = treeNodeService.updateNode(dto, token);
            return ResponseEntity.ok(
                    Response.success("更新成功", node)
            );
        } catch (AuthenticationException e) {
            return ResponseEntity.status(401).body(
                    Response.error(401, e.getMessage())
            );
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(
                    Response.error(400, e.getMessage())
            );
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(
                    Response.error(500, "系统错误：" + e.getMessage())
            );
        }
    }

    @Operation(summary = "删除节点", description = "删除指定节点及其子节点")
    @ApiResponse(responseCode = "200", description = "删除成功")
    @ApiResponse(responseCode = "400", description = "请求参数错误")
    @ApiResponse(responseCode = "401", description = "未授权")
    @ApiResponse(responseCode = "500", description = "系统错误")
    @DeleteMapping("delete/{id}")
    public ResponseEntity<Response<?>> deleteNode(
            @PathVariable("id") Integer id,
            @RequestHeader("Authorization") String token
    ) {
        try {
            treeNodeService.deleteNode(id, token);
            return ResponseEntity.ok(Response.success("节点删除成功", null));
        } catch (AuthenticationException e) {
            return ResponseEntity.status(401).body(Response.error(401, e.getMessage()));
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(Response.error(400, e.getMessage()));
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Response.error(500, "系统错误：" + e.getMessage()));
        }
    }
}